import { Link, useNavigate } from "react-router-dom";
import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Select,
    DatePicker,
    Table,
    Tag,
    Space,
    Popconfirm,
} from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";

import locale from "antd/es/date-picker/locale/zh_CN";
import "./index.scss";

import img404 from "@/assets/error.png";
import { useEffect, useState } from "react";
import { http } from "@/utils";
import { useStore } from "@/store";
import { observer } from "mobx-react-lite";
const { Option } = Select;
const { RangePicker } = DatePicker;

const Article = () => {
    //使用navigate进行页面跳转
    const navigate = useNavigate();
    //筛选功能
    const onFinish = (values) => {
        const { status, channel_id, date } = values;
        const sparams = {};
        if (channel_id) {
            sparams.channel_id = channel_id;
        }
        if (status === -1) {
            sparams.status = null;
        } else {
            sparams.status = status;
        }

        if (date) {
            sparams.begin_pubdate = date[0].format("YYYY-MM-DD");
            sparams.end_pubdate = date[1].format("YYYY-MM-DD");
        }
        //修改params状态参数，触发获取文章列表接口再次发起
        setParams({
            ...params,
            ...sparams,
        });
    };

    // 频道列表仓库
    const { channelStore } = useStore();

    //文章列表数据
    const [article, setArticle] = useState({
        list: [],
        count: 0,
    });
    //查询文章参数管理
    const [params, setParams] = useState({
        page: 1,
        per_page: 10,
    });
    //发送接口请求获取文章列表
    useEffect(() => {
        async function getArticleList() {
            const res = await http.get("/mp/articles", { params });
            const { results, total_count } = res.data;
            setArticle({
                list: results,
                count: total_count,
            });
        }
        getArticleList();
    }, [params]);
    //分页
    const pageChange = (page) => {
        // 拿到当前页参数 修改params 引起接口更新
        setParams({
            ...params,
            page,
        });
    };

    //删除
    const delArticle = async (a) => {
        await http.delete(`/mp/articles/${a.id}`);
        // 更新列表
        setParams({
            page: 1,
            per_page: 10,
        });
    };
    //编辑
    const goEdit = (e) => {
        navigate(`/publish?id=${e.id}`);
    };
    //表格
    const columns = [
        {
            title: "封面",
            dataIndex: "cover",
            width: 120,
            render: (cover) => {
                return (
                    <img
                        src={cover.images[0] || img404}
                        width={80}
                        height={60}
                        alt=''
                    />
                );
            },
        },
        {
            title: "标题",
            dataIndex: "title",
            width: 220,
        },
        {
            title: "状态",
            dataIndex: "status",
            render: (data) => <Tag color='green'>审核通过</Tag>,
        },
        {
            title: "发布时间",
            dataIndex: "pubdate",
        },
        {
            title: "阅读数",
            dataIndex: "read_count",
        },
        {
            title: "评论数",
            dataIndex: "comment_count",
        },
        {
            title: "点赞数",
            dataIndex: "like_count",
        },
        {
            title: "操作",
            key: "action",
            render: (data) => {
                return (
                    <Space size='middle'>
                        <Button
                            type='primary'
                            shape='circle'
                            onClick={() => goEdit(data)}
                            icon={<EditOutlined />}
                        />
                        <Popconfirm
                            title='你确定要删除吗?'
                            onConfirm={() => delArticle(data)}
                            okText='确定'
                            cancelText='取消'>
                            <Button
                                type='primary'
                                danger
                                shape='circle'
                                icon={<DeleteOutlined />}
                            />
                        </Popconfirm>
                    </Space>
                );
            },
        },
    ];

    return (
        <div>
            <Card
                title={
                    <Breadcrumb separator='>'>
                        <Breadcrumb.Item>
                            <Link to='/'>首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>内容管理</Breadcrumb.Item>
                    </Breadcrumb>
                }
                style={{ marginBottom: 20 }}>
                <Form
                    initialValues={{ status: -1 }}
                    onFinish={onFinish}
                    autoComplete='off'>
                    <Form.Item name='status' label='状态'>
                        <Radio.Group>
                            <Radio value={-1}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>审核通过</Radio>
                            <Radio value={3}>审核失败</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item name='channel_id' label='频道'>
                        <Select
                            placeholder='请选择文章频道'
                            style={{ width: 200 }}>
                            {channelStore.channels.map((item) => (
                                <Option key={item.id} value={item.id}>
                                    {item.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name='date' label='日期'>
                        <RangePicker locale={locale} />
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 1,
                        }}>
                        <Button type='primary' htmlType='submit'>
                            筛选
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            <Card title={`根据筛选条件共查询到${article.count} 条结果：`}>
                <Table
                    rowKey={(record) => record.id}
                    columns={columns}
                    dataSource={article.list}
                    pagination={{
                        position: ["bottomCenter"],
                        current: params.page,
                        pageSize: params.per_page,
                        total: article.count,
                        onChange: pageChange,
                    }}
                />
            </Card>
        </div>
    );
};

export default observer(Article);
